'use strict'

const koaTool = require('../../commons/koa_tool')
const adminAuthService = require('../services/admin_auth')
const {
  ROLE_PERMISSION_CODE
} = require('./admin_permission')

module.exports = {
  /**
   * 
   * @param {import('koa/lib/application')} ctx 用户token验证
   * @param {*} next 
   */
  auth: async function (ctx, next) {
    //console.log('ctx.headers:',ctx.headers)
    let token = ctx.headers['x-token'];
    //console.log('token:',token)
    if (!token) {
      token = ctx.request.query['token'] || ctx.request.body['token'];
    }

    if (!token) {
      return koaTool.fail(ctx, 'auth.invalid_token', 401);
    }

    token = token.trim();
    let [authValidateEroor, _user] = await adminAuthService.validateToken(token);
    if (authValidateEroor) {
      return koaTool.fail(ctx, authValidateEroor, 401);
    }

    // 将获取的用户信息放到 req 对象中 以便下方可随时获取到
    ctx.state._user = _user;
    ctx.state._user_id = _user.id;
    ctx.state._permissions = ROLE_PERMISSION_CODE[_user.role_type]; // 直接从代码中换出 当前角色 对应的权限列表 XXX: （如果为了要更加灵活，可以从数据库中获取）
    ctx.state._user.role = {
      _id: _user.role_type,
      name: _user.role_type,
      permission_codes: ctx.state._permissions,
    }
    // console.log(`auth succ admin user info ${JSON.stringify(_user)}`);

    return next();
  },

  /**
   * 检查当前用户的权限  （根据角色 换 权限）
   * // [permission, ...]
   * @param {[]} requiredPermissions 
   */
  isPermitted(requiredPermissions = []) {

    const {
      checkPermision
    } = require('./admin_permission');

    function onDenied(ctx) {
      return koaTool.fail(ctx, 'common.Illegal_operation', 403);
    }

    function withPermissions(ctx) {
      return ctx.state._permissions || [];
    }

    return function (ctx, next) {
      const currUserPermission = withPermissions(ctx);

      if (checkPermision(currUserPermission, requiredPermissions)) {
        return next()
      }

      return onDenied(ctx);
    }
  }
};